var express = require('express');
var router = express.Router();
// 引入
var filmsService = require('../service/filmsService');

// 增加
router.post('/', async function (req, res) {//'/add'改为'/'
    let { name, ename, type, area, time, upDate, year, score, count, want, intro, director, actor, images } = req.body;
    director = JSON.parse(director);
    actor = JSON.parse(actor);
    images = JSON.parse(images);
    console.log(director);
    // { name, ename, type, area, time, upDate, year, score, count, want, intro, director, actor, images }
    let data = await filmsService.insert({ name, ename, type, area, time, upDate, year, score, count, want, intro, director, actor, images });
    res.send({ data });
});

// 搜索
router.get('/', async function (req, res) {//去掉find   
    // get提交获取参数的方法是req.query
    console.log("req.query", req.query);
    let { type, value, current, pageSize } = req.query;
    let searchObj = {};
    searchObj[type] = { $regex: value };
    let data = await filmsService.find(searchObj,
        { current: current || 1, pageSize: pageSize || 5 }//current页面显示的搜索出来的结果的第几页，若不从search.js文件中上传current : 1，页面显示的搜索出来的结果页码是当前页面开始搜索的第几页搜索出来的结果的第几页，就不会从第一页开始显示搜索出来的结果，如果结果数据比较少，页面就不会显示，因为大于第一页都没有内容
    );
    res.send({ data });
});

// 搜索
router.get('/all', async function (req, res) {//去掉find    
    let data = await filmsService.findAll();
    res.send({
        data
    });
});
// findAll
// 修改搜索
router.get('/:id', async function (req, res) {//将'/findById'改为'/:id'
    // get提交获取参数的方法是req.query
    console.log("req.query", req.query);

    let { id } = req.params;//动态路径    变为'/:id'的才改为params
    let data = await filmsService.findById(id);
    console.log("修改搜索参数：", id);
    res.send({ data });
});

// 删除
router.delete('/:id', async function (req, res) {//post-delete  '/remove'-'/:id'
    // get提交获取参数的方法是req.query
    console.log("req.body::", req.body);
    let { id } = req.params;

    let data = await filmsService.remove(id);

    console.log('data:', data);
    res.send({ data });

});
// 修改
router.put('/:id', async function (req, res) {//post-put  '/update'-'/:id'
    console.log("req.body:", req.body);
    let { id } = req.params;
    let { name, ename, type, area, time, upDate, year, score, count, want, intro, director, actor, images } = req.body;

    director = JSON.parse(director);
    actor = JSON.parse(actor);
    images = JSON.parse(images);

    let data = await filmsService.update(id, { name, ename, type, area, time, upDate, year, score, count, want, intro, director, actor, images });

    res.send({ data });

});

// 通过id查找
router.get('/:id', async function (req, res) {
    let { id } = req.params;
    let data = await filmsService.findById(id);
    res.send({ data });
});


module.exports = router;